package net.stock.utils;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * @author naim
 */
public class StockUtils {
    private static Logger log = Logger.getLogger(StockUtils.class.getName());

    private static final String USER_EMAIL_REQUEST_ATTRIBUTE = "userEmail";
    private static final String LOGOUT_LINK_REQUEST_ATTRIBUTE = "logoutLink";

    public static final String HOME_PAGE = "/req/welcome";
    public static final String ERROR_PAGE = "/req/error";

    public static DateTimeZone timeZone = DateTimeZone.forID("Asia/Dhaka");

    public static final String DSEBD_TXT_URL = "http://admin.dsebd.org/admin-real/datafile/quotes.txt";
//    public static final String DSEBD_TXT_URL = "http://localhost:8080/test_data.txt";

    public static int CONNECT_TIMEOUT = 10000;    // 10 seconds, max for google url-fetch
    public static int READ_TIMEOUT = 10000;

    public static final String ADMIN_EMAIL = "mdnhuda@gmail.com";



    public static void setLoggedUserEmail(HttpServletRequest req, String userEmail) {
        req.setAttribute(USER_EMAIL_REQUEST_ATTRIBUTE, userEmail);
    }

    public static String getLoggedUserEmail(HttpServletRequest req) {
        return (String) req.getAttribute(USER_EMAIL_REQUEST_ATTRIBUTE);
    }

    public static void setLogoutLinkInRequest(HttpServletRequest req, String logoutLink) {
        req.setAttribute(LOGOUT_LINK_REQUEST_ATTRIBUTE, logoutLink);
    }

    public static boolean notEmpty(String str) {
        return str != null && str.length() > 0;
    }

    public static int toDateInt(DateTime dateTime) {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd");
        formatter.withZone(timeZone);
        return Integer.parseInt(formatter.print(dateTime));
    }

    public static Float parseFloat(String str) {
        try {
            return Float.parseFloat(str);
        } catch (NumberFormatException nfe) {
            return null;
        }
    }

    public static boolean priceHasChangedSignificantly(Float f1, Float f2) {
        if (f1 == null || f1.intValue() == 0) {
            return false;
        }
        if (f2 == null || f2.intValue() == 0) {
            return false;
        }

        return Math.abs((f1 - f2) / f1) > 0.01;
    }

    public static final int ERROR_TYPE_NOT_YET_REQUESTED = 1;
    public static final int ERROR_TYPE_REQUEST_NOT_YET_ACCEPTED = 2;
    public static final int ERROR_TYPE_UNAUTHORIZED = 3;
    public static final int ERROR_TYPE_ALREADY_EXISTS = 4;

    public static String getErrorMsg(int type) {
        switch(type) {
            case ERROR_TYPE_NOT_YET_REQUESTED:
                return "You do not have the right to use this service. Please request to the administrator.";
            case ERROR_TYPE_REQUEST_NOT_YET_ACCEPTED:
                return "Your request has not yet been accepted by the administrator. " +
                        "A mail will be sent to your mailbox when it is processed.";
            case ERROR_TYPE_UNAUTHORIZED:
                return "You do not have sufficient role to access this page.";

            case ERROR_TYPE_ALREADY_EXISTS:
                return "Already exists!";

            default:
                return "There has been an error!";
        }
    }

    public static void writeToResponseOutputStream(HttpServletResponse response, String body) throws IOException {
        byte[] buffer = body.getBytes("UTF-8");
        response.setContentType("text/plain");
        response.setContentLength(buffer.length);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.addHeader("Cache-Control", "must-revalidate");
        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Cache-Control", "no-store");
        response.setDateHeader("Expires", 0);

        response.getOutputStream().write(buffer);
        response.getOutputStream().close();
    }
}
